package com.yb.flowable.filter;

import com.yb.flowable.common.JwtUtils;
import com.yb.flowable.common.LoginUser;
import com.yb.flowable.common.LoginUserUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.UUID;

/**
 * @author biaoyang
 * @Date
 */
@Component
public class MyFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //获取请求头里的token信息
        String jwtToken = request.getHeader("Authorization");
        //判断token是否存在
        if (StringUtils.isBlank(jwtToken)) {
            //如果请求头没有token信息,那就去参数获取token信息
            jwtToken = request.getParameter("accessToken");
            //这里为了方便测试,直接在这里添加token
        }
        //判断并解析token
        LoginUser loginUser = JwtUtils.verifySignatureGetPayload(jwtToken);
        //判断解析是否成功(能解析出对象不为空即成功)
        if (Objects.nonNull(loginUser)) {
            //设置用户信息到用户工具中(这里仅仅只是获取用户token信息,如果没有就不设置用户工具里,这里由于特殊原因,没有token也可以访问,只是我在业务代码会处理)
            LoginUserUtils.setUser(loginUser);
        }
        //执行下面的filter(必要的,实测如果不设置导致swagger无内容)
        filterChain.doFilter(request, response);
    }

//    public static void main(String[] args) {
//        //这里直接手动初始化
//
//        List<String> roles = Arrays.asList("member");
//        List<String> perms = Arrays.asList("view");
//        LoginUser user = new LoginUser("1", "jack", roles, perms);
//        String accessToken = JwtUtils.createAccessToken(user);
//        System.err.println("========1===" + accessToken);
//
//
//        List<String> roles2 = Arrays.asList("leaderC");
//        List<String> perms2= Arrays.asList("all");
//        LoginUser user2 = new LoginUser("2", "rose", roles2, perms2);
//        String accessToken2 = JwtUtils.createAccessToken(user2);
//        System.err.println("========2===" + accessToken2);
//
//        List<String> roles3 = Arrays.asList("leaderB");
//        List<String> perms3 = Arrays.asList("all");
//        LoginUser user3 = new LoginUser("3", "tom", roles3, perms3);
//        String accessToken3 = JwtUtils.createAccessToken(user3);
//        System.err.println("========3===" + accessToken3);
//
//        List<String> roles4 = Arrays.asList("leaderA");
//        List<String> perms4 = Arrays.asList("view", "update");
//        LoginUser user4 = new LoginUser("4", "jackson", roles4, perms4);
//        String accessToken4 = JwtUtils.createAccessToken(user4);
//        System.err.println("========4===" + accessToken4);
//
//    }
}
